

package com.base.lib.base.adapter

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.loadmore.LoadMoreStatus

/**
 * PagingDataAdapter添加Footer
 * @since  2021/5/21
 */
abstract class CustomerFooterAdapter<T:RecyclerView.ViewHolder> : RecyclerView.Adapter<T>() {

    var loadState: LoadMoreStatus = LoadMoreStatus.Complete
        set(loadState) {
            if (field != loadState) {
                val oldItem = displayLoadStateAsItem(field)
                val newItem = displayLoadStateAsItem(loadState)

                if (oldItem && !newItem) {
                    notifyItemRemoved(0)
                } else if (newItem && !oldItem) {
                    notifyItemInserted(0)
                } else if (oldItem && newItem) {
                    notifyItemChanged(0)
                }
                field = loadState
            }
        }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): T {
        return onCreateViewHolder(parent, loadState)
    }

    override fun onBindViewHolder(holder: T, position: Int) {
        onBindViewHolder(holder, loadState)
    }

    abstract fun onCreateViewHolder(parent: ViewGroup, loadState: LoadMoreStatus): T;

    abstract fun onBindViewHolder(holder: T, loadState: LoadMoreStatus);

    override fun getItemCount(): Int = if (displayLoadStateAsItem(loadState)) 1 else 0

    protected fun displayLoadStateAsItem(loadState: LoadMoreStatus): Boolean {
        return loadState == LoadMoreStatus.Loading || loadState == LoadMoreStatus.Fail
    }
}